<?php

namespace App\Http\Filters;

use Illuminate\Database\Eloquent\Builder;

class InstructorsFilter extends AbstractFilter
{

    public const CENTERS_ID = 'centers_id';
    public const STATUS = 'status';
    public const SPORT = 'sport';
    public const SECOND_NAME = 'second_name';

    /**
     * @return array
     */
    protected function getCallbacks(): array
    {
        return [
            self::STATUS => [$this, self::STATUS],
            self::CENTERS_ID => [$this, self::CENTERS_ID],
            self::SPORT => [$this, self::SPORT],
            self::SECOND_NAME => [$this, self::SECOND_NAME],
        ];
    }


    public function status(Builder $builder, $value)
    {
        $this->filterLogic($builder, $value, self::STATUS);
    }

    public function centers_id(Builder $builder, $value)
    {
        $this->filterLogic($builder, $value, self::CENTERS_ID);
    }

    public function sport(Builder $builder, $value)
    {
       $this->filterLogic($builder, $value, self::SPORT);
    }
    public function second_name(Builder $builder, $value)
    {
       $this->filterLogic($builder, $value, self::SECOND_NAME);
    }

    protected function filterLogic(Builder $builder, $value, $column)
    {
        $builder->where(function ($query) use ($value, $column){

            foreach ($value as $key => $val) {
            if ($key > 0) {
                $query->orWhere($column, trim($val));
            } else {
                if ($column === 'second_name') {
                    $query->where($column, 'like', '%' . trim($val) . '%');
                } else {
                    $query->where($column, trim($val));
                }
            }

        }
        });


    }
}
